//
//  PersonalViewController.m
//  UESTCPioneer
//
//  Created by Sway on 14-3-5.
//  Copyright (c) 2014年 Sway. All rights reserved
//

#import "PersonalViewController.h"
#import "LeveyTabBarController.h"
#import "PersonalInformation.h"
#import "MyCollection.h"
#import "CheckForSuggestion.h"
#import "MyMessage.h"
#import "BirthCare.h"
#import "DailyCare.h"
#import "StartActivity.h"
#import "PublishNotice.h"
#import "MyNotice.h"
#import "PartyFeeController.h"
#import "NewsDetailViewController.h"
#import "ApplyViewController.h"

//------------Sakura begin 2014-08-11 党费缴纳-------------
//#import "PayViewController.h"
//------------Sakura end 2014-08-11 党费缴纳--------------

@interface PersonalViewController ()
{
    NSArray *nameArray;
    NSArray *cellIcon;
    NSArray *pushArray;
    NSString *score;
    NSUInteger flag;
}
@end

@implementation PersonalViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}
//
#pragma mark - view display entranc

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSString *userId = [constant getUserId];
    flag = [[userId substringFromIndex:userId.length - 1] intValue];//管理员id号末尾是1和2，如果不是管理员则把部分功能隐藏
    
    self.PersonalTableView.delegate = self;
    self.PersonalTableView.dataSource = self;
//    nameArray = @[@"个人信息",@"我的收藏",@"查看意见",@"我的消息",@"缴交党费",@"生日关怀",@"日常关怀",@"发起活动",@"发布通知",@"我的通知"];
    //------------Sakura 2014-08-11 begin 党费缴纳-------------
      nameArray = @[@"个人信息",@"我的收藏",@"查看意见",@"我的消息",@"生日关怀",@"日常关怀",@"发起活动",@"发布通知",@"我的通知",@"关于软件"];
    cellIcon = @[@"inf.png",@"pcollect.png",@"view.png",@"mymsg.png",@"birth.png",@"care.png",@"activity.png",@"sendmsg.png",@"mynotice.png",@"software.png"];
    pushArray = @[@"personalinformation",@"mycollection",@"checkforsuggestion",@"mymessage",@"birthcare",@"dailycare",@"startactivity",@"publishnotice",@"mynotice",@"aboutsoft"];
    //------------Sakura end --------------
    if(IS_IOS7){
        NSLog(@"[[[UIDevice currentDevice]systemVersion]floatValue] = %f",[[[UIDevice currentDevice]systemVersion]floatValue]);
         self.PersonalTableView.separatorInset = UIEdgeInsetsZero;
    }
    NSLog(@"[[[UIDevice currentDevice]systemVersion]floatValue] = %f",[[[UIDevice currentDevice]systemVersion]floatValue]);
    
    
    [self.view addSubview:self.department];
    [self.view addSubview:self.topBackground];
    [self.view addSubview:self.PersonalTableView];
    [self.view addSubview:self.headPicture];
    [self.view addSubview:self.name];
    [self setPersonalInformation];
    
    [self addJiFenView];
    
//    [self.view addSubview:self.jifen];
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    [self.leveyTabBarController.navigationItem setTitle:@"个人"];
        [self.leveyTabBarController.navigationItem setLeftBarButtonItem:nil];
    [self.view setUserInteractionEnabled:YES];
    [self.PersonalTableView setScrollEnabled:YES];
    
    
    UIView *customView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 44, 44)];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:customView.bounds];
    [customView addSubview:button];
    [button setImage:[UIImage imageNamed:@"logout.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(logout:) forControlEvents:UIControlEventTouchUpInside];
    [button setImageEdgeInsets:UIEdgeInsetsMake(12, 12, 12, 12)];
    UIBarButtonItem *right=[[UIBarButtonItem alloc]initWithCustomView:customView];
    [self.leveyTabBarController.navigationItem setRightBarButtonItem:right];
    [self getJifen];
}

-(void)viewWillDisappear:(BOOL)animated{
    [self.leveyTabBarController.navigationItem setRightBarButtonItem:Nil];
}

-(void)addJiFenView{

    CGFloat h = CGRectGetMaxY(_topBackground.frame);
    
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, h, 120, 35)];
    [self.view addSubview:view];
    
    UILabel * textLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 0, 70, 35)];
    [textLabel setText:@"我的积分:"];
    [textLabel setTextColor:[UIColor grayColor]];
    [textLabel setFont:[UIFont fontWithName:@"MarkerFelt-Thin" size:14.0f]];
    [view addSubview:textLabel];
    [view addSubview:self.jifen];
}

- (void)setPersonalInformation
{
    if ((NSString *)[[constant getPersonalInfo] objectForKey:@"headpicture"] != nil)
        self.headPictureImage = [[constant getPersonalInfo] objectForKey:@"headpicture"];
    if ((NSString *)[[constant getPersonalInfo] objectForKey:@"branch"] != nil)
        self.department.text = [[constant getPersonalInfo] objectForKey:@"branch"];
    if ((NSString *)[[constant getPersonalInfo] objectForKey:@"name"] != nil)
        self.name.text = [[constant getPersonalInfo] objectForKey:@"name"];
}//获得个人信息的接口

#pragma mark -datasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    

    if (flag == 0) {
        return 3;
    }
    else
        return 4;
}
//------------Sakura 2014-08-11 begin 党费缴纳-------------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            return 4;
            break;
        case 1 :
            return 2;
            break;
        case 2 :
            return (flag == 0) ? 1 : 3;
            break;
        default:
            break;
    }
    return 1;

}
//------------Sakura end --------------
- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return IS_IOS7 ? 6 : 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (!section)
        return 0.1;
    return 5;
}
//------------Sakura 2014-08-11 begin 党费缴纳-------------
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"PersonalCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    CGFloat y = (self.PersonalTableView.rowHeight - 30) / 2;
    CGFloat x = 10;
    UIImageView *leftImage = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, 30, 30)];
//    leftImage.center = CGPointMake(32, self.PersonalTableView.rowHeight/2.0);
//    NSLog(@"self.PersonalTableView.rowHeight = %f",self.PersonalTableView.rowHeight);
    int offset = 0;
    if (flag == 0) {
        offset = 3;
    }
    switch (indexPath.section) {
        case 0:
            cell.textLabel.text=nameArray[indexPath.row];
            leftImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",cellIcon[indexPath.row]]];
            break;
        case 1 :
            cell.textLabel.text=nameArray[indexPath.row + 4];
            leftImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",cellIcon[indexPath.row + 4]]];
            break;
        case 2:
            cell.textLabel.text=nameArray[indexPath.row + 6 +offset];
            leftImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",cellIcon[indexPath.row + 6 + offset]]];
            break;
        case 3:
            cell.textLabel.text=nameArray[indexPath.row + 9];
            leftImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",cellIcon[indexPath.row + 9]]];
            break;
        default:
            break;
    }
    [cell.contentView addSubview:leftImage];
    return cell;
}
//------------Sakura end --------------

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    self.PersonalTableView.rowHeight = 44.0f;
    return 44.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    id aCell;
    switch (indexPath.section) {
        case 0:
            switch (indexPath.row) {
                case 0:
                    aCell = [[PersonalInformation alloc] initWithStyle:UITableViewStyleGrouped];
                    break;
                case 1:
                    aCell = [[MyCollection alloc] init];
                    break;
                case 2:
                    aCell = [[CheckForSuggestion alloc] init];
                    break;
                case 3:
                    aCell = [[MyMessage alloc] init];
                    break;

                default:
                    break;
            }
            break;
        case 1:
            switch (indexPath.row) {
                case 0:
                    aCell = [[BirthCare alloc] init];
                    break;
                case 1:
                    aCell = [[DailyCare alloc] init];
                    break;

                default:
                    break;
            }
            break;
            //------------ Sakura-2014-08-11 begin 党费缴纳-------------
        case 2:
            if (flag == 0) {
                [self getSoftWare];
                return;
            }
            switch (indexPath.row) {
                case 0:
                    aCell = [[StartActivity alloc] initWithStyle:UITableViewStyleGrouped];
                    break;
                case 1:
                    aCell = [[PublishNotice alloc] init];
                    break;
                case 2:
                    aCell = [[MyNotice alloc] init];
                    break;
                default:
                    break;
            }
            break;
            //------------ Sakura end ---------------
        case 3:
            [self getSoftWare];
        default:
            break;
    }
    [self.leveyTabBarController.navigationController pushViewController:aCell animated:YES];
    [self.PersonalTableView deselectRowAtIndexPath:indexPath animated:YES];

}

#pragma mark - property lazy initialization

- (UIImageView *)topBackground
{
    if (!_topBackground)
    {
        _topBackground = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
        _topBackground.image = [UIImage imageNamed:@"personbg.png"];
    }
    return _topBackground;
}

- (void)setTopBackgroundImage:(UIImage *)topBackgroundImage{
    self.topBackground.image = topBackgroundImage;
}

- (UIImageView *)headPicture
{
    if (!_headPicture)
    {
        _headPicture = [[UIImageView alloc] initWithFrame:CGRectMake(250, self.topBackground.frame.size.height-45, 60, 60)];
        _headPicture.layer.shadowOffset = CGSizeMake(0, 0);
        _headPicture.layer.shadowOpacity = 0.5;
        _headPicture.layer.shadowColor = [UIColor blackColor].CGColor;
        _headPicture.layer.borderWidth = 3.0f;
        _headPicture.layer.borderColor = [[UIColor lightGrayColor] CGColor];
        _headPicture.layer.shadowRadius = 6.0;
//        [_headPicture.layer setCornerRadius:2.0];
//
//        
//        CALayer * layer = [_imgvPhoto layer];
//        layer.borderColor = [
//                             [UIColor whiteColor] CGColor];
//        layer.borderWidth = 5.0f;
//        //添加四个边阴影
//        _imgvPhoto.layer.shadowColor = [UIColor blackColor].CGColor;
//        _imgvPhoto.layer.shadowOffset = CGSizeMake(0, 0);
//        _imgvPhoto.layer.shadowOpacity = 0.5;
//        _imgvPhoto.layer.shadowRadius = 10.0;给iamgeview添加阴影 < wbr > 和边框
//        //添加两个边阴影
//        _imgvPhoto.layer.shadowColor = [UIColor blackColor].CGColor;
//        _imgvPhoto.layer.shadowOffset = CGSizeMake(4, 4);
//        _imgvPhoto.layer.shadowOpacity = 0.5;  
//        _imgvPhoto.layer.shadowRadius = 2.0;
        
        
        
        
        
        
        
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        //GCD中可以将一组相关联的操作定义到一个群组中，定义群组中之后，当所有线程完成时，可以获得通知
        //1>定义群组
        dispatch_group_t group = dispatch_group_create();
        
        //2>定义群组的异步任务
        NSString* filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",[constant getUserName]]];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        if ([fileManager fileExistsAtPath:filePath]) {
            _headPicture.image = [UIImage imageWithContentsOfFile:filePath];
        }else{
            _headPicture.image = [UIImage imageNamed:@"persontx.png"];
        }
   
        NSString * headPath = [constant getUserHeadUrl];
        __block NSData * data;
        if (headPath.length>0) {
                 dispatch_group_async(group, queue, ^{
            NSString * str = [NSString stringWithFormat:@"http://115.28.239.113:8080%@",headPath];
            data = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]];
                     });
            dispatch_group_notify(group, queue, ^{
                NSLog(@"处理完成了!");
                
                dispatch_sync(dispatch_get_main_queue(), ^{
                    NSString* filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",[constant getUserName]]];
                    
                    [data writeToFile:filePath atomically:YES];
                    _headPicture.image = [UIImage imageWithData:data];
                });
            });
        }else{
            
        }
    }
    return _headPicture;
}

- (void)setHeadPictureImage:(UIImage *)headPictureImage
{
    self.headPicture.image = headPictureImage;
}

- (UITableView *)PersonalTableView{
    if (!_PersonalTableView) {
        _PersonalTableView = [[UITableView alloc] initWithFrame:CGRectMake(0,self.topBackground.frame.size.height+35, 320,[UIApplication sharedApplication].keyWindow.frame.size.height - 20 - 44 - _topBackground.frame.size.height - _name.frame.size.height - self.leveyTabBarController.tabBar.frame.size.height - 35) style:UITableViewStyleGrouped];
    }

    return _PersonalTableView;
}

- (UILabel *)name
{
    if (!_name)
    {
        _name = [[UILabel alloc] initWithFrame:CGRectMake(0,self.department.frame.origin.y-35, 235, 35)];
        _name.textAlignment = NSTextAlignmentRight;
        _name.font = [UIFont systemFontOfSize:18];
        _name.textColor = [UIColor whiteColor];
        _name.text = @"Katherine Pierce";
        if (!IS_IOS7)
            _name.backgroundColor = [UIColor clearColor];
    }
    return _name;
}

- (UILabel *)department
{
    if (!_department)
    {
        _department = [[UILabel alloc] initWithFrame:CGRectMake(0, self.topBackground.frame.size.height, 250, 35)];
        _department.textAlignment = NSTextAlignmentRight;
        _department.font = [UIFont systemFontOfSize:14];
        _department.textColor = [UIColor colorWithRed:119.0/255.0 green:123.0/255.0 blue:134.0/255.0 alpha:1];
        _department.text = @"Undefined Department";
        _department.backgroundColor = self.PersonalTableView.backgroundColor;
        self.view.backgroundColor =self.PersonalTableView.backgroundColor;
        if (!IS_IOS7)
            _department.backgroundColor = [UIColor clearColor];
    }
    return _department;
}

-(UILabel*)jifen{
    if (!_jifen) {
        _jifen = [[UILabel alloc] initWithFrame:CGRectMake(78, 0, 40, 35)];
        _jifen.textAlignment = NSTextAlignmentLeft;
        _jifen.font = [UIFont fontWithName:@"AmericanTypewriter" size:17.0f];
//        _jifen.font = [UIFont systemFontOfSize:17];
        _jifen.textColor = [UIColor redColor];
        NSString *str = @"";
        _jifen.text = [str stringByAppendingString: [NSString stringWithFormat:@"%@",[constant getPersonScore]]];
        _jifen.backgroundColor = self.PersonalTableView.backgroundColor;
        self.view.backgroundColor =self.PersonalTableView.backgroundColor;
        if (!IS_IOS7)
            _department.backgroundColor = [UIColor clearColor];
    }
    return _jifen;
}

//-(UIImageView*)jifenImg{
//    if (!_jifenImg) {
//        _jifenImg = [[UIImageView alloc] initWithFrame:CGRectMake(2, self.topBackground.frame.size.height+10, 12, 12)];
//        _jifenImg.image = [UIImage imageNamed:@"info.png"];
//        _jifenImg.contentMode = UIViewContentModeScaleAspectFill;
//    }
//    return _jifenImg;
//}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - logout function 
-(void)logout:(id)sender{
    
    /*修改*/
    UIAlertView * alterView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定注销？"
                                                   delegate:self cancelButtonTitle:@"确定"
                                                   otherButtonTitles:@"取消", nil];
    [alterView show];
   
    
//    NSUserDefaults * defaultData = [NSUserDefaults standardUserDefaults];
//    [defaultData setBool:NO forKey:@"login"];
//    [defaultData synchronize];
//    [[NSNotificationCenter defaultCenter]postNotificationName:@"logout" object:nil];
     /**/
}
#pragma mark UIAlterView代理方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 1) {
        return;
    }else{
        NSUserDefaults * defaultData = [NSUserDefaults standardUserDefaults];
        [defaultData setBool:NO forKey:@"login"];
        [defaultData synchronize];
        
//        if([JXXMPP sharedInstance].isLogined){
//            [[JXXMPP sharedInstance] logout];
//        }
        [self logoutAction];

        //
//        [[NSNotificationCenter defaultCenter]postNotificationName:@"logout" object:nil];
    }
}

- (void)logoutAction
{
    __weak PersonalViewController *weakSelf = self;
    [self showHudInView:self.view hint:@"正在退出..."];
    [[EaseMob sharedInstance].chatManager asyncLogoffWithCompletion:^(NSDictionary *info, EMError *error) {
        [weakSelf hideHud];
        if (error) {
            NSLog(@"退出失败!");
            NSLog(@"退出交流error.description = %@",error.description);
            [weakSelf showHint:error.description];
        } else {
            //            [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
            NSLog(@"退出成功!");
             [[ApplyViewController shareController] clear];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"logout" object:nil];
        }
    } onQueue:nil];
}


#pragma mark -
#pragma mark 获取个人积分

-(void)getJifen{
    NSDictionary *request = @{@"type": @"getPersonScore",
                              @"userId":[constant getUserId]};
    [NetworkCenter AFRequestWithData:request SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
        NSLog(@"get jifen sucess");
        NSDictionary *dics = [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:nil][0];
        NSString *str = @"";
        _jifen.text = [str stringByAppendingString: [NSString stringWithFormat:@"%@",[dics objectForKey:@"result"]]];
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"get jifen fail");
    }];
}

-(void)getSoftWare{
    NSDictionary *request = @{@"type": @"getAppAbout"};
    [NetworkCenter AFRequestWithData:request SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
        NSLog(@"sucess");
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:nil][0];
        NewsDetailViewController *aboutSoft = [[NewsDetailViewController alloc] initWithImgUrlArr:nil title:[dic objectForKey:@"title"] content:[dic objectForKey:@"content"]];
        [self.leveyTabBarController.navigationController pushViewController:aboutSoft animated:YES];
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"fail");
    }];
}

@end
